package com.nus.servlets;

import com.nus.beans.Leave;
import com.nus.beans.User;
import com.nus.database.LeavesDBManager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/23/12
 * Time: 1:00 AM
 * To change this template use File | Settings | File Templates.
 */
public class CancelLeavesServlet extends AbstractServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Enumeration e = request.getParameterNames();
        String leaveDate;
        List<Leave> cancelLeaves = new ArrayList<Leave>();
        Leave tmpLeave;
        String errorMessage = null;
        boolean isCancelable = true;

        Connection connection = getUserDatabaseConnection(request);
        LeavesDBManager leavesDBManager = new LeavesDBManager(connection);
        User user = (User) request.getSession().getAttribute("user");

        while (e.hasMoreElements()) {
            leaveDate = String.valueOf(e.nextElement());
            tmpLeave = new Leave(user.getUserId(), new Date(Long.parseLong(leaveDate)));
            cancelLeaves.add(tmpLeave);
        }

        //check leave status
        if (!cancelLeaves.isEmpty()) {
            for (Leave leave : cancelLeaves) {
                if (!leavesDBManager.isLeaveCanceleble(leave)) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    errorMessage = "Leave on date " + formatter.format(leave.getDate()) + " is not cancelable. Cancel request rejected.";
                    request.setAttribute("ERROR_MESSAGE", errorMessage);
                    isCancelable = false;
                    break;
                }
            }

            if (isCancelable) {
                for (Leave leave : cancelLeaves) {
                    leavesDBManager.cancelLeave(leave);
                }
            }

        } else {
            errorMessage = "Please select some leave to cancel.";
        }

        leavesDBManager.close();
        request.setAttribute("ERROR_MESSAGE", errorMessage);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("viewLeavesHistory.do");
        requestDispatcher.forward(request, response);
    }
}
